package com.xuecheng.system.controller;

import cn.hutool.core.util.StrUtil;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.LoginDto;
import com.xuecheng.commons.model.vo.LoginVo;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.utils.AuthInfoHolder;
import com.xuecheng.system.domain.User;
import com.xuecheng.web.exception.BusinessException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import com.xuecheng.system.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

/**
 * <p>
 * 用户信息前端控制器
 * </p>
 *
 * @author itheima
 */
@Slf4j
@RestController
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    // 登录
    @PostMapping("/login")
    public ResponseResult<LoginVo> login(@RequestBody LoginDto loginDto) {
        // 调用service实现登录
        return userService.login(loginDto);
    }

    //用于其他服务远程调用获取用户信息
    @GetMapping("/user")
    public User getName(@RequestParam Long id) {
        return userService.getById(id);
    }

    //验证手机验证码
    @PostMapping("/user/changePwd/verify")
    public ResponseResult verify(String verifyCode) {
        //获取当前用户手机号
        String phone = getName(AuthInfoHolder.getUserId()).getPhone();
        //校验是否过期
        if (!redisTemplate.hasKey("code:"+phone)) {
            throw new BusinessException(ErrorCode.NOTFOUND);
        }
        //取出redis中的验证码
        String code = (String) redisTemplate.opsForValue().get("code:"+phone);
        //校验验证码
        if (!StrUtil.equals(verifyCode, code)) {
            throw new BusinessException(ErrorCode.DATAERROR);
        } else {
            return ResponseResult.okResult();
        }
    }

    //修改用户密码
    @PostMapping("/user/changePwd/{verifyToken}")
    public ResponseResult changePwd(@PathVariable("verifyToken") String token, @RequestBody Map<String, String> map) {
        return userService.changePwd(map);
    }
}
